package bar.dark.lee.stats;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.select.SelectActivity;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;

public class StatsCategoryListActivity extends SuperActivity
{
	private ListView listView;
	
	private ArrayList<StatsCategoryData> list;
	
	private int inoutFlag;
	
	private int year;
	private int month;
	
	private int typeFlag = 0;
	private int assetFlag = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setFindView();
		new ShowDialog().execute(0);
	}

	private void setFindView()
	{
		setContentView(R.layout.stats_category_list_activity);
		
		listView = (ListView) findViewById(R.id.statsCategoryListview);
	}
	
	private void setData()
	{
		Calendar cal = Calendar.getInstance();
		year = cal.get(Calendar.YEAR);
		month = cal.get(Calendar.MONTH);
		
		Intent intent = getIntent();
		
		inoutFlag = intent.getIntExtra(StatsActivity.STATS_CATEGORY_FLAG, -1);
		list = intent.getParcelableArrayListExtra(StatsCategoryActivity.STATS_CATEGORY_DATA);
		year = intent.getIntExtra(StatsActivity.SELECT_YEAR, year);
		month = intent.getIntExtra(StatsActivity.SELECT_MONTH, month);
		typeFlag = intent.getIntExtra(StatsAssetActivity.TYPE_FLAG, 0);
		assetFlag = intent.getIntExtra(StatsAssetActivity.ASSET_FLAG, 0);
		
		if (list.size() >= 2)
		{
			list = sortList(list);
		}
	}
	
	private ArrayList<StatsCategoryData> sortList(ArrayList<StatsCategoryData> list)
	{
		ArrayList<StatsCategoryData> sortedList = new ArrayList<StatsCategoryData>();
		StatsCategoryData maxData = new StatsCategoryData();
		maxData.setCategory(list.get(0).getCategory());
		maxData.setMoney(list.get(0).getMoney());
		maxData.setMoneyKind(list.get(0).getMoneyKind());
		maxData.setPercent(list.get(0).getPercent());
		int maxIndex = -1;
		int size = list.size();
		
		for (int i=0; i<size; i++)
		{
			for (int j=0; j<size; j++)
			{
				if (Double.parseDouble(maxData.getMoney()) <= Double.parseDouble(list.get(j).getMoney()))
				{
					maxData.setCategory(list.get(j).getCategory());
					maxData.setMoney(list.get(j).getMoney());
					maxData.setMoneyKind(list.get(j).getMoneyKind());
					maxData.setPercent(list.get(j).getPercent());
					maxIndex = j;
				}
			}
			
			StatsCategoryData tempData = new StatsCategoryData();
			tempData.setCategory(maxData.getCategory());
			tempData.setMoney(maxData.getMoney());
			tempData.setMoneyKind(maxData.getMoneyKind());
			tempData.setPercent(maxData.getPercent());
			
			sortedList.add(tempData);
			
			maxData.setMoney("0");
			list.get(maxIndex).setMoney("0");
		}
		
		return sortedList;
	}
	
	private class StatsCategoryAdapter extends ArrayAdapter<StatsCategoryData> implements OnItemClickListener
	{
		public StatsCategoryAdapter(Context context, int textViewResourceId,
				ArrayList<StatsCategoryData> list)
		{
			super(context, textViewResourceId, list);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				v = getLayoutInflater().inflate(R.layout.list_item_stats_category, null);
			}
			
			StatsCategoryData data = list.get(position);
			
			TextView name = (TextView) v.findViewById(R.id.listStatsCategoryName);
			TextView money = (TextView) v.findViewById(R.id.listStatsCategoryMoney);
			TextView percent = (TextView) v.findViewById(R.id.listStatsCategoryPercent);
			
			if (inoutFlag == StatsActivity.STATS_ASSET_MANAGER)
			{
				name.setText(data.getMoneyKind());
			}
			else
			{
				name.setText(data.getCategory());
			}
			
			money.setText(BDUtil.getWon(data.getMoney()) + shape);
			
			percent.setText("(" + data.getPercent() + "%)");
			
			return v;
		}
		
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3) {
			Intent intent = new Intent(StatsCategoryListActivity.this, SelectActivity.class);
			intent.putExtra(StatsActivity.STATS_CATEGORY_FLAG, inoutFlag);
			intent.putExtra(StatsActivity.SELECT_YEAR, year);
			intent.putExtra(StatsActivity.SELECT_MONTH, month);
			intent.putExtra(StatsActivity.SELECT_CATEGORY, list.get(pos).getCategory());
			intent.putExtra(StatsActivity.SELECT_MONEYKIND, list.get(pos).getMoneyKind());
			intent.putExtra(StatsAssetActivity.TYPE_FLAG, typeFlag);
			intent.putExtra(StatsAssetActivity.ASSET_FLAG, assetFlag);
			startActivity(intent);
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(StatsCategoryListActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				setData();
				return 0;
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == 0)
			{
				if (inoutFlag == StatsActivity.STATS_IN)
				{
					setTitle("수입 카테고리 리스트");
				}
				else if (inoutFlag == StatsActivity.STATS_OUT)
				{
					setTitle("지출 카테고리 리스트");
				}
				else if (inoutFlag == StatsActivity.STATS_MOVE)
				{
					setTitle("이동 카테고리 리스트");
				}
				else if (inoutFlag == StatsActivity.STATS_ASSET_MANAGER)
				{
					setTitle("자산 리스트");
				}
				
				TextView textTitle = (TextView)findViewById(R.id.listStatsCategoryTitle);
				TextView textTotalMoney = (TextView)findViewById(R.id.listStatsCategoryTotalMoney);
				
				switch (inoutFlag) 
				{
					case StatsActivity.STATS_OUT:
						textTitle.setText( (month+1) + "월 총 지출 금액 : ");
						break;
					case StatsActivity.STATS_IN:
						textTitle.setText( (month+1) + "월 총 수입 금액 : ");		
						break;
					case StatsActivity.STATS_MOVE:
						textTitle.setText( (month+1) + "월 총 이동 금액 : ");
						break;
					case StatsActivity.STATS_ASSET_MANAGER:
						
						String typeStr = "";
						String assetStr = "";
						
						if (typeFlag == 0)
						{
							typeStr = "지출";
						}
						else if (typeFlag ==1)
						{
							typeStr = "수입";
						}
						else if (typeFlag ==2)
						{
							typeStr = "이동";
						}
						
						if (assetFlag == 0)
						{
							assetStr = "통장";
						}
						else if (assetFlag == 1)
						{
							assetStr = "체크카드";
						}
						else if (assetFlag == 2)
						{
							assetStr = "신용카드";
						}
						else if (assetFlag == 3)
						{
							assetStr = "현금";
						}
						
						setTitle(typeStr + " / " + assetStr);
						
						textTitle.setText( (month+1) + "월 " + assetStr + " 총 " + typeStr + " 금액 : ");
						break;
					default:
						break;
				}
				
				BigDecimal totalMoney = BigDecimal.ZERO;
				for (int i=0; i<list.size(); i++)
				{
					try {
						totalMoney = totalMoney.add(new BigDecimal(list.get(i).getMoney()));
					} catch (Exception e) 
					{
						continue;
					}
				}
				textTotalMoney.setText(BDUtil.getWon(totalMoney + "") + shape);
				
				if (list.size() <= 0)
				{
					View nodataView = getLayoutInflater().inflate(R.layout.view_no_result, null);
					listView.addHeaderView(nodataView, null, false);
					listView.setHeaderDividersEnabled(false);
				}
				
				StatsCategoryAdapter adapter = new StatsCategoryAdapter(
						StatsCategoryListActivity.this, R.layout.list_item_stats_category, list);
				listView.setAdapter(adapter);
				listView.setOnItemClickListener(adapter);
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_STATS);
		startActivity(intent);
	}
}
